import {HandlerDetails, View, WebContentsView} from "electron";
import {getScrollbarStyles} from "../../helper/utils.js";


export default class BaseView {
  view: WebContentsView | undefined = undefined;


  init(session: string) {
    this.view = new WebContentsView({
      webPreferences: {
        partition: session,
      },
    });

    this.view.setBackgroundColor("#fff");
    this.view.setVisible(true)

    this.view.webContents.on("did-navigate", (event: unknown, url: string) => { this.onDidNavigate(event, url) });
    this.view.webContents.on("did-navigate-in-page", (event: unknown, url: string)=> { this.onDidNavigateInPage(event, url) });

    this.view.webContents.on("did-finish-load", ()=> { this.onDidFinishLoad() });

    this.view.webContents.setWindowOpenHandler(this.onOpenNewWindow);
  }

  onDidNavigate = (event: unknown, url: string) => {

  };
  onDidNavigateInPage = (event: unknown, url: string) => {
  };

  onDidFinishLoad = () => {
    this.view?.webContents.insertCSS(getScrollbarStyles()).catch(err => {
      console.error('注入滚动条样式失败:', err);
    });
  };

  onOpenNewWindow = ({ url }: HandlerDetails) => {
    this.loadURL(url);
    return { action: "deny" } as { action: "deny" };
  };

  get parentView(): View | undefined {
    return undefined
  }

  destroyView() {
    if (this.view && this.parentView) {
      this.view.webContents.close();
      this.parentView.removeChildView(this.view);
    }
    this.view = undefined;
  }

  send(channel: string, data: any) {
    this.view?.webContents.send(channel, data);
  }

  getBounds(): Electron.Rectangle {
    if (!this.view) {
      throw new Error("窗口不存在");
    }
    return this.view.getBounds();
  }

  setBounds(bounds: Electron.Rectangle) {
    if (!this.view) return;
    this.view.setBounds(bounds);
  }

  async goBack() {
    if (!this.view) {
      return false
    }
    const { webContents } = this.view;
    if (webContents.canGoBack()) {
      webContents.goBack();
      return true;
    } else {
      this.destroyView();
      return false;
    }
  }

  async reload() {
    if (!this.view) {
      return
    }
    this.view.webContents.reload();
  }

  loadURL(url: string) {
    if (!this.view) return;

    // 1. Stop current navigation
    this.view.webContents.stop();
    // this.urlCache.clear()
    // 2. Load a new url
    this.view.webContents.loadURL(url);
  }

  show() {
    if (!this.view || !this.parentView) return;
    // console.log("show", this.constructor.name)
    this.parentView.addChildView(this.view);
  }

  hide() {
    if (!this.view || !this.parentView) return;
    this.parentView.removeChildView(this.view);
  }
}
